package com.lx.cloudzuul.web;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.bean.Result;
import com.lx.dm.util.JWTUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyinfoFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 127.0.0.1/user/login/myinfo?...
        String path = request.getServletPath();
        System.out.println("path = " + path);
        return path.matches("/[^/]+/login/myinfo");
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String jwt = request.getHeader("Authorization");
        Result result;
        try{
            Claims claims = JWTUtil.parseJWT(jwt);
            result = new Result(1, "已登陆", claims);
        }catch (Exception e){
            result = new Result(0, "未登陆", null);
        }

        // 请求不会发送到目标资源
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(200);
        try {
            String json = new ObjectMapper().writeValueAsString(result);
            ctx.getResponse().setContentType("application/json;charset=utf-8");
            ctx.setResponseBody(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
